<template>
  <!-- 全局公共导入框 -->
  <el-dialog :title="$t('导入包裹')" :visible.sync="show" :before-close="cancel" width="400px" append-to-body>
    <el-upload
      :limit="1"
      ref="upload"
      :action="action"
      :on-change="({ raw }) => (file = raw)"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">{{ $t('将文件拖到此处，或点击上传') }}</div>
      <div class="el-upload__tip text-center" slot="tip"></div>
    </el-upload>

    <slot></slot>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">
        {{ $t('确定') }}
      </el-button>
      <el-button @click="cancel">
        {{ $t('取消') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { importPackageByRoute } from '@/api/orderManage/batchDispatch'

export default {
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      action: '',
      file: null,
    }
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.$refs['upload'].uploadFiles = []
        })
      }
    },
  },
  methods: {
    handleSubmit() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })

      if (!this.file) {
        return this.$message.error(this.$t('请选择'))
      }
      const formData = new FormData()
      formData.append('file', this.file)
      formData.append('batchId', this.formData.id)

      importPackageByRoute(formData)
        .then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.cancel()
            this.$emit('getList')
          }
        })
        .finally(() => {
          loading.close()
        })
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style></style>
